﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HardToolApp.Model;
using System.IO.Ports;

namespace HardToolApp.Tool
{
    internal class JsonOrderVM : JsonConverter
    {
        /// <summary>
        ///     写入Json数据
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }

        /// <summary>
        ///     读Json数据
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            Type[] types = new Type[] { typeof(UartModel), typeof(ADCModel), typeof(IICMasterModel), typeof(IICSlaveModel),
            typeof(SPIMasterModel),typeof(SPISlaveModel),typeof(GpioModel.GPIO),typeof(PwmModel.PWM)};
            if (objectType == typeof(Peripheral))
            {
                var jsonObject = JObject.Load(reader);
                object target = null;
                JToken commType;
                if (jsonObject.TryGetValue("commType", out commType))
                {
                    target = System.Activator.CreateInstance(types[commType.ToObject<int>() - 1]);
                }
                serializer.Populate(jsonObject.CreateReader(), target);
                return target;
            }
            return null;
        }
        /// <summary>
        ///     是否可以转换
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Peripheral);
        }
    }
}
